import express from 'express';
import fs from 'node:fs';
import path from 'node:path';
import { JSONFilePreset } from 'lowdb/node';

const __dirname = import.meta.dirname;

// 项目配置
const config = {
    // port: 0,            // 端口号
    // public: '',         // 静态资源目录
    // database: '',       // 数据库文件目录
};              

// 配置文件的相对路径
const relativeConfigPath = '../config/server.config.json';              

// 解析配置文件
function parseConfigFile() {
    const jsonData = fs.readFileSync(path.resolve(__dirname, relativeConfigPath), 'utf-8');
    Object.assign(config, JSON.parse(jsonData));                // 解析配置文件后，更新项目配置
    // 解析数据库根目录
    const configFilePath = path.resolve(__dirname, relativeConfigPath);
    const configFileDirPath = configFilePath.replace(/(?:\/|\\)[^\/\\]+(?=$)/, '');
    const database = path.resolve(configFileDirPath, config.database);
    config.database = database;         // 数据库目录
}

// 添加静态资源目录
function setStaticResourcesDirectory() {
    const relativePublicPath = config.public;
    const fullPath = path.resolve(__dirname, relativeConfigPath);
    const dirPath = fullPath.replace(/(?:\/|\\)[^\/\\]+(?=$)/, '');
    const dstPath = path.resolve(dirPath, relativePublicPath);
    config.public = dstPath;
    app.use(express.static(config.public));
}

// 程序入口
function main() {
    parseConfigFile();
    setStaticResourcesDirectory();
    app.use(express.json());                // 使用中间件解析post请求的请求体内容
}

/* 创建应用 */
const app = express();

/* 其他逻辑 */
main();                         


/* 绑定路由 */


// 获取歌曲列表
app.get('/songs', async (res, req) => {
    const dbFilePath = path.resolve(config.database, 'songs.json');
    const db = await JSONFilePreset(dbFilePath, {
        total: 0,
        currentId: 0,
        lists: [],
    });
    await db.write();
    req.json({
        code: 200,
        msg: 'success',
        data: db.data.lists,
    });
})

// 根据id查询歌曲信息
app.get('/songs/:id', async (req, res) => {
    const id = parseInt(req.params.id);                 // req.params对象中的数据都是string类型，需要手动转化
    let result = null;
    const dbFilePath = path.resolve(config.database, 'songs.json');
    const db = await JSONFilePreset(dbFilePath, {
        total: 0,
        currentId: 0,
        lists: [],
    });
    const index = db.data.lists.findIndex(it => it.id===id);
    if (index!==-1) {
        result = db.data.lists[index];
    }
    await db.write();
    if (result) {
        res.json({
            code: 200,
            msg: 'success',
            data: result,
        });
    } else {
        res.json({
            code: 400,
            msg: 'id不存在',
            data: result,
        });
    }
})

// 插入一条歌曲记录
app.post('/songs', async (req, res) => {
    // console.log(req.body);                           // req.body中包含post请求请求体中json类型的数据
    const bodyKeys = Object.keys(req.body);
    const targetKeys = ['href', 'name', 'singer', 'songName', 'imgUrl'];        // 要求的字段
    const isValid = targetKeys.every(key => bodyKeys.includes(key));
    if (!isValid) {
        res.json({
            code: 400,
            msg: `字段缺失，必要字段为：${targetKeys.join(', ')}`,
            data: null,
        });
        return;
    }
    const dbFilePath = path.resolve(config.database, 'songs.json');
    const db = await JSONFilePreset(dbFilePath, {
        total: 0,
        currentId: 0,
        lists: [],
    });
    // 插入一条新纪录
    db.data.lists.push({
        id: db.data.currentId + 1,
        href: req.body.href,
        name: req.body.name,
        singer: req.body.singer,
        songName: req.body.songName,
        imgUrl: req.body.imgUrl,
    });
    db.data.total++;
    db.data.currentId++;
    await db.write();

    res.json({
        code: 200,
        msg: 'success',
        data: null,
    });
})

// 根据id删除歌曲记录
app.delete('/songs/:id', async (req, res) => {
    const id = parseInt(req.params.id);
    const dbFilePath = path.resolve(config.database, 'songs.json');
    const db = await JSONFilePreset(dbFilePath, {
        total: 0,
        currentId: 0,
        lists: [],
    });

    const list = db.data.lists;

    const index = list.findIndex(it => it.id===id);

    if (index==-1) {
        // id对应的记录不存在
        res.json({
            code: 400,
            msg: 'id不存在',
            data: null,
        });
        await db.write();
        return;
    }

    db.data.lists.splice(index, 1);

    db.data.total--;

    res.json({
        code: 200,
        msg: 'success',
        data: null,
    });

    await db.write();
})

// 修改歌曲记录
// app.put('/songs', async (req, res) => {
// });




app.listen(config.port, () => {
    console.log(`服务启动成功，端口地址为：${config.port}...`);
});